<template>
  <business-layout title='操作票记录'>
    <div class='table-operator' slot='query'>
      <a-form :form='form' layout='inline' @submit='handleQueryData'>
        <a-form-item label=''>
          <a-select allowClear style='width: 200px;' placeholder='请选择状态' v-decorator="['status']">
            <a-select-option value='2'>已处理</a-select-option>
            <a-select-option value='1'>待处理</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label=''>
          <a-input placeholder='请输入名称' v-decorator='["name"]' />
        </a-form-item>
        <a-form-item>
          <a-button type='primary' html-type='submit'>
            <a-icon type='search' />
            查询
          </a-button>

          <a-button html-type='reset' @click='handleResetData'>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <div slot='btns'>
      <a-button type='primary' icon='plus' @click='visible = true'>新增</a-button>
    </div>

    <s-table
      ref='table'
      size='default'
      rowKey='key'
      :columns='columns'
      :data='loadData'
      showPagination='auto'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='description' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>

      <span slot='createdTime' slot-scope='text'>
        {{ text | dayjs }}
      </span>

      <span slot='status' slot-scope='text'>
        <a-tag :color='text | statusFilterStyle'>
          {{ text | statusFilter }}
        </a-tag>
      </span>

      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handlePreview(record)'>预览</a>
        </template>
        <template>
          <a-divider type='vertical' />
          <a @click='handleExport(record)'>导出</a>
        </template>
        <template v-if='+record.status === 1'>
          <a-divider type='vertical' />
          <a @click='handleComplate(record)'>完成</a>
        </template>
        <template v-if='+record.status === 2'>
          <a-divider type='vertical' />
          <a @click='handlePreviewFile(record)'>预览附件</a>
        </template>
      </span>
    </s-table>

    <create-operation
      ref='CreateOperation'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      @cancel='handleCancel'
      @ok='handleOk'
    />

    <preview-file
      ref='PreviweFile'
      :previewVisible='previweFileVisible'
      :model='model'
      @cancel='previweFileVisible = false'
    />

    <operation-complate
      :loading='operationComplateLoading'
      ref='OperationComplate'
      :model='model'
      :edit='edit'
      :visible='operationVisible'
      @cancel='handleOperationCancel'
      @ok='handleOperationOk' />
  </business-layout>
</template>

<script>
import moment from 'moment'
import OperationComplate from '../modules/OperationComplate.vue'
import { STable, Ellipsis } from '@/components'
import { downloadAvatar } from '@/api/workerOrder'
import { completeTicket, createTicket, findByPage } from '@/api/operationTicket'
import PreviewFile from '../modules/PreviewFile.vue'

import CreateOperation from '../modules/CreateOperation.vue'

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '名称',
    dataIndex: 'name'
  },
  {
    title: '模板名称',
    dataIndex: 'templateName'
  },
  {
    title: '创建人',
    dataIndex: 'createdUser'
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    scopedSlots: { customRender: 'createdTime' }
  },
  {
    title: '发令人',
    dataIndex: 'sender'
  },
  {
    title: '受令人',
    dataIndex: 'receiver'
  },
  {
    title: '发令时间',
    dataIndex: 'sendTime'
  },
  {
    title: '出票时间',
    dataIndex: 'ticketingTime'
  },
  {
    title: '完成时间',
    dataIndex: 'completedTime'
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateOperation,
    PreviewFile,
    OperationComplate
  },
  data() {
    this.columns = columns
    return {
      visible: false,
      confirmLoading: false,
      operationComplateLoading: false,
      form: this.$form.createForm(this),
      mdl: null,
      model: null,
      operationVisible: false,
      edit: false,
      previweFileVisible: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return findByPage(requestParameters).then(res => {
          return res
        })
        // return new Promise((resolve, reject) => {
        //   resolve({
        //     list: [{}],
        //     pageNo: 1,
        //     total: 1
        //   })
        // })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
    statusFilter(val) {
      if (+val === 1) {
        return '待处理'
      }
      return '已处理'
    },
    statusFilterStyle(val) {
      if (+val === 1) {
        return 'orange'
      }
      return 'green'
    }
  },
  created() {
  },
  mounted() {
    if (this.$route.query.mark) {
      this.form.setFieldsValue({
        status: '1'
      })
      this.handleQueryData()
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleResetData() {
      this.queryParam = {}
      this.form.resetFields()
      this.$refs.table.refresh()
    },
    handlePreview(value) {
      this.model = value
      this.previweFileVisible = true
    },
    handleComplate(value) {
      this.ticketId = value.id
      this.edit = true
      this.operationVisible = true
    },
    handlePreviewFile(value) {
      this.model = value
      this.edit = false
      this.operationComplateLoading = true
      this.model.attachementFileName = value.attachmentFile
      this.operationVisible = true
      setTimeout(()=>{
        this.operationComplateLoading = false
      }, 5000)
    },
    handleExport(value) {
      window.open(downloadAvatar({ fileName: value.ticketFile }))
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleOperationOk() {
      const form = this.$refs.OperationComplate.form
      this.operationComplateLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 新增
          completeTicket({
            ticketId: this.ticketId,
            ...values
          }).then(res => {
            this.visible = false
            // 重置表单数据
            form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()

            this.$message.success('新增成功')
            this.model = null
            this.operationVisible = false
          }).finally(() => {
            this.operationComplateLoading = false
          })
        } else {
          this.operationComplateLoading = false
        }
      })
    },
    handleOk() {
      const form = this.$refs.CreateOperation.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          // 新增
          createTicket(values).then(res => {
            this.visible = false
            // 重置表单数据
            form.resetFields()
            // 刷新表格
            this.$refs.table.refresh()

            this.$message.success('新增成功')
          }).finally(() => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleOperationCancel() {
      this.operationVisible = false
      this.model = null
      const form = this.$refs.OperationComplate.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.CreateOperation.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.success(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleQueryData(e) {
      e.preventDefault()
      const form = this.form
      const that = this
      const queryObj = {}
      form.validateFields((error, values) => {
        Object.keys(values).forEach(key => {
          if (values[key]) {
            queryObj[key] = values[key]
          }
        })
        this.queryParam = queryObj
        that.$refs.table.refresh()
      })
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang='less' scoped>
.table-tab {

}
</style>
